/**
 * 
 */
package userController;


import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;

import javax.swing.JOptionPane;

import mail.MailSender;

import org.apache.commons.lang3.StringUtils;

import constants.Constants;
import userEntity.LoginEntity;
import userEntity.UserEntity;
import userLogic.CreateUserLogic;
import userLogic.LoginLogic;
import userLogic.UserLogic;
import validator.Validator;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

/**
 * @author Yokesh Kumar
 *
 */
public class SysAdminController implements Initializable {

	@FXML
	private Label userName;
	@FXML
	private Stage sysAdminStage;
	@FXML
	private StackPane sysAdminStackPane;
	
	
	@FXML
	private TextField PhoneNo,PhoneNoA;
	@FXML
	private Label searchLabel,loginIdInvalid,phoneInvalid;
	@FXML
	private TextField LoginID,LoginIdA;
	@FXML
	private TextField role,roleA;
	@FXML
	private TextField emailId;
	@FXML
	private TextField name,nameA;
	@FXML
	private TextField PhoneNumber,PhoneNumberA;
	@FXML
	private Label userNameL,PhoneL,roleL,NameL,message,DMessage,ph1;
	@FXML
	private Button deactivate;
	@FXML
	private TextField DLoginId,DLoginIdA;
	@FXML
	private Pane ActivateUserPane;
	
	private static String mailId;
	
	LoginLogic login = new LoginLogic();
	UserLogic logic = new UserLogic();
    UserEntity user = new UserEntity();

	/**
	 * @param sysAdminStackPane the sysAdminStackPane to set
	 */
	public void setSysAdminStackPane(Node node) {
		sysAdminStackPane.getChildren().setAll(node);
	}
	
	/**
	 * 
	 * @param name
	 */
	public void setName(String name){
		//userName = new Label(name);
		userName.setText(name);
	}
	
	/**
	 * 
	 * @param Stage
	 */
	public void SetStage(Stage Stage)
	{
		this.sysAdminStage=Stage;
	}
	
	/**
	 * This method is invoked when system admin clicks EditProfile 
	 * Precondition: system admin is logged in
	 * Postcondition: editProfile() in UserController is invoked
	 * @param event
	 */
	@FXML
	public void EditProfile(ActionEvent event)
	{
		UserController uController = new UserController();
		uController.editProfile(Navigator.getPhoneNumber());
	}
	
	/**
	 * This method is invoked when system admin clicks Change Password
	 * Precondition: system admin is logged in
	 * Postcondition: changePassword() in UserController is invoked
	 * @param event
	 */
	@FXML
	public void ChangePassword(ActionEvent event)
	{
		UserController ucController = new UserController();
		ucController.changePassword();
	}
	/**
	 * 	This method is executed when System admin clicks create
	 * employee button
	 * Precondition: System admin is logged in
	 * Postcondition: Create employee stackpane is loaded
	 * @param event
	 * @throws IOException
	 */
	@FXML
	public void createUser(ActionEvent event) throws IOException{
		Navigator.loadStackPane(Navigator.SYSCreateEmp);
	    
	}
	
	/**
	 * This method is executed when system admin clicks
	 * deactivate user button
	 * Precondition: System admin is logged in
	 * Postcondition: deactivate user stackpane is loaded
	 * @param event
	 * @throws IOException
	 */
	@FXML
	public void deactivateUser(ActionEvent event) throws IOException{
		page=2;
		Navigator.loadStackPane(Navigator.SYSDeactivateUser);
	}
	
	/**
	 * This method is executed when system admin clicks 
	 * search user button while deactivating user
	 * Precondition: System admin is deactivating the user
	 * Postcondition: displays details of the user to be deactivated
	 * @param event
	 */
	@FXML
	public void searchUserForDeactivation(ActionEvent event){
		try
		{
		int useLoginId = 0;
		UserLogic logic = new UserLogic();
		UserEntity user = new UserEntity();
		LoginLogic login = new LoginLogic();
		LoginEntity lentity = new LoginEntity();
		searchLabel.setText("");
		userNameL.setDisable(true);
		   PhoneL.setDisable(true);
		   NameL.setDisable(true);
		   roleL.setDisable(true);
		   DLoginId.setDisable(true);
		   PhoneNumber.setDisable(true);
		   name.setDisable(true);
		   role.setDisable(true);
		   deactivate.setDisable(true);
		   ph1.setDisable(true);
		   DMessage.setText("");
		   DLoginId.setText("");
		   PhoneNumber.setText("");
		   name.setText("");
		   role.setText("");
		
		CreateUserLogic create = new CreateUserLogic();
		if(LoginID.getText().isEmpty() && PhoneNo.getText().isEmpty()) {
			DMessage.setText("Please enter either PhoneNumber or LoginId");}
		else
		{
			if(!PhoneNo.getText().isEmpty())
			{
				if(Validator.validatePhoneNumber(PhoneNo.getText().trim()))
				{
					if(!create.checkPhoneNumber("+1".concat(PhoneNo.getText().trim())))
					{
						if(create.checkUserStatus("+1".concat(PhoneNo.getText().trim())))
						{
						   PhoneNumber.setText(PhoneNo.getText().trim());
						   
							user = logic.fetchUserDetails("+1".concat(PhoneNo.getText().trim()));
							if(user.getEmailID() != null && !StringUtils.isEmpty(user.getEmailID())){
								mailId = user.getEmailID();
							}
						   DLoginId.setText(login.fetchLoginId("+1".concat(PhoneNo.getText().trim())));
						   name.setText(user.getName());
						   String Role = user.getUserType();
						   if(Role.equals(Constants.MANAGER))
							   role.setText("Manager");
						   else if(Role.equals(Constants.CLERK))
							   role.setText("Clerk");
						   else if(Role.equals(Constants.CUSTOMER))
							   role.setText("Customer");
						   else
							   role.setText("Sytem Admin");
						   userNameL.setDisable(false);
						   PhoneL.setDisable(false);
						   NameL.setDisable(false);
						   roleL.setDisable(false);
						   DLoginId.setDisable(false);
						   PhoneNumber.setDisable(false);
						   name.setDisable(false);
						   role.setDisable(false);
						   deactivate.setDisable(false);
						   ph1.setDisable(false);
						   DMessage.setText("");
						}
						else
						{
							phoneInvalid.setText("User is already diactivated");
							DMessage.setText("");
						}
					}
					else
					{
						phoneInvalid.setText("Phone number does not exist");
						DMessage.setText("");
						if(!LoginID.getText().isEmpty())
						{
							useLoginId = 1;
						}
					}
				}
				else
				{
					phoneInvalid.setText("Invalid entry");
					DMessage.setText("");
				}
			}
			else
			{
				useLoginId = 1;
			}
			if(useLoginId == 1)
			{
				if(!create.checkLoginId(LoginID.getText().trim()))
				{
					if(create.checkStatus(LoginID.getText().trim()))
					{
						DLoginId.setText(LoginID.getText().trim());
						lentity.setLoginId(LoginID.getText().trim());
						String Phone = login.fetchPhoneNumber(lentity);
						Phone = Phone.substring(2);
						PhoneNumber.setText(Phone);
						user = logic.fetchUserDetails("+1".concat(PhoneNumber.getText().trim()));
						if(user.getEmailID() != null && !StringUtils.isEmpty(user.getEmailID())){
							mailId = user.getEmailID();
						}
						name.setText(user.getName());
						String Role = user.getUserType();
						   if(Role.equals(Constants.MANAGER))
							   role.setText("Manager");
						   else if(Role.equals(Constants.CLERK))
							   role.setText("Clerk");
						   else if(Role.equals(Constants.CUSTOMER))
							   role.setText("Customer");
						   else
							   role.setText("Sytem Admin");
						userNameL.setDisable(false);
						   PhoneL.setDisable(false);
						   NameL.setDisable(false);
						   roleL.setDisable(false);
						   DLoginId.setDisable(false);
						   PhoneNumber.setDisable(false);
						   role.setDisable(false);
						   name.setDisable(false);
						   deactivate.setDisable(false);
						   DMessage.setText("");
						   ph1.setDisable(false);
						   loginIdInvalid.setText("");
						   phoneInvalid.setText("");
						   PhoneNo.setText("");
					}
					else
					{
						loginIdInvalid.setText("User is already deactivated");
						DMessage.setText("");
					}
				}
				else
				{
					loginIdInvalid.setText("LoginId does not exist");
					DMessage.setText("");
				}}
			
		}}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			DMessage.setText("Connection Failed..Try Again!");
		}
		
	}
	
	/**
	 * This method is executed when system admin clicks
	 * deactivate button while deactivating user
	 * Precondition: user details displayed by the searchUserForDeactivation method
	 * Postcondition: user is deactivated
	 * @param event
	 * @throws SQLException
	 */
	@FXML
	public void deActivateUser(ActionEvent event){
		try {
			logic.deActivate("+1".concat(PhoneNumber.getText().trim()));
			if(mailId != null && !StringUtils.isEmpty(mailId)){
				String text = "Dear SuperRent User, Your login is deactivated by Admin. Please contact SuperRent Admin for further Details. Ph no: +19999999999 , Email - ??";
				String subject = "Your SuperRent Login deactivated";
				MailSender.send(text, subject, mailId);
			}
			mailId= "";
		System.out.println("user deactivated");
		searchLabel.setText("User deactivated");
		searchLabel.setTextFill(Color.GREEN);
		}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			searchLabel.setText("Connection Failed..Try Again!");
		}
		
	}
	
	/**
	 * This method is executed when system admin clicks
	 * reset password button
	 * Precondition: system admin is logged in
	 * Postcondition: reset password stackpane is loaded
	 * @param event
	 * @throws IOException
	 */
	@FXML
	public void resetPassword(ActionEvent event) throws IOException{
		// invoke user controller
		Navigator.setInitailize(true);
		Navigator.loadStackPane(Navigator.SYSUpdatePassword);
		
	}
	
	public static int page=0;
	
	/**
	 * This method is executed when system admin clicks
	 * activate user button
	 * Precondition: system admin is logged in
	 * Postcondition: activate user stackpane is loaded
	 * @param event
	 * @throws IOException
	 */
	@FXML
	public void activateUser(ActionEvent event) throws IOException{
		page=1;
		Navigator.loadStackPane(Navigator.SYSActivate);
		
	}
	
	/**
	 * This method is executed when system admin clicks 
	 * search user button while activating user
	 * Precondition: system admin is activating user
	 * Postcondition: displays details for the user to be activated
	 * @param event
	 */
	@FXML
	public void searchUserForActivation(ActionEvent event){
		try
		{
		UserLogic logic = new UserLogic();
		UserEntity user = new UserEntity();
		LoginLogic login = new LoginLogic();
		LoginEntity lentity = new LoginEntity();
		message.setText("");
		ActivateUserPane.setDisable(true);
		PhoneNumberA.setText("");
		DLoginIdA.setText("");
		nameA.setText("");
		roleA.setText("");
		CreateUserLogic create = new CreateUserLogic();
		if(LoginIdA.getText().isEmpty() && PhoneNoA.getText().isEmpty()) {
			searchLabel.setText("Please enter either PhoneNumber or LoginId");}
		else
		{
			if(!PhoneNoA.getText().isEmpty())
			{
				if(Validator.validatePhoneNumber(PhoneNoA.getText().trim()))
				{
					if(!create.checkPhoneNumber("+1".concat(PhoneNoA.getText().trim())))
					{
						if(!create.checkUserStatus("+1".concat(PhoneNoA.getText().trim())))
						{
						   PhoneNumberA.setText(PhoneNoA.getText().trim());
						   user = logic.fetchUserDetails("+1".concat(PhoneNoA.getText().trim()));
						   if(user.getEmailID() != null && !StringUtils.isEmpty(user.getEmailID())){
								mailId = user.getEmailID();
							}
						   DLoginIdA.setText(login.fetchLoginId("+1".concat(PhoneNoA.getText().trim())));
						   nameA.setText(user.getName());
						   String RoleA = user.getUserType();
						   if(RoleA.equals(Constants.MANAGER))
							   roleA.setText("Manager");
						   else if(RoleA.equals(Constants.CLERK))
							   roleA.setText("Clerk");
						   else if(RoleA.equals(Constants.CUSTOMER))
							   roleA.setText("Customer");
						   else
							   roleA.setText("Sytem Admin");
						   ActivateUserPane.setDisable(false);
						   searchLabel.setText("");
						   phoneInvalid.setText("");
						   loginIdInvalid.setText("");
							LoginIdA.setText("");
						}
						else
						{
							phoneInvalid.setText("User is already active");
							searchLabel.setText("");
							loginIdInvalid.setText("");
							LoginIdA.setText("");
						}
					}
					else
					{
						if(LoginIdA.getText().trim().isEmpty())
						{
						phoneInvalid.setText("Phone number does not exist");
						searchLabel.setText("");
						}
						else
						{

							if(!create.checkLoginId(LoginIdA.getText().trim()))
							{
								if(!create.checkStatus(LoginIdA.getText().trim()))
								{
									DLoginIdA.setText(LoginIdA.getText().trim());
									lentity.setLoginId(LoginIdA.getText().trim());
									String Phone = login.fetchPhoneNumber(lentity);
									Phone = Phone.substring(2);
									PhoneNumberA.setText(Phone);
									user = logic.fetchUserDetails("+1".concat(PhoneNumberA.getText().trim()));
									nameA.setText(user.getName());
									String RoleA = user.getUserType();
									   if(RoleA.equals(Constants.MANAGER))
										   roleA.setText("Manager");
									   else if(RoleA.equals(Constants.CLERK))
										   roleA.setText("Clerk");
									   else if(RoleA.equals(Constants.CUSTOMER))
										   roleA.setText("Customer");
									   else
										   roleA.setText("Sytem Admin");
									ActivateUserPane.setDisable(false);
									searchLabel.setText("");
									loginIdInvalid.setText("");
									phoneInvalid.setText("");
									PhoneNoA.setText("");
									
								}
								else
								{
									loginIdInvalid.setText("User is already active");
									searchLabel.setText("");
									phoneInvalid.setText("");
									PhoneNoA.setText("");
								}
							}
							else
							{
								loginIdInvalid.setText("LoginId does not exist");
								phoneInvalid.setText("Phone Number does not exist");
								searchLabel.setText("");
							}
						}
					}
				}
				else
				{
					phoneInvalid.setText("Invalid entry");
					searchLabel.setText("");
				}
			}
			else
			{
				if(!create.checkLoginId(LoginIdA.getText().trim()))
				{
					if(!create.checkStatus(LoginIdA.getText().trim()))
					{
						DLoginIdA.setText(LoginIdA.getText().trim());
						lentity.setLoginId(LoginIdA.getText().trim());
						String Phone = login.fetchPhoneNumber(lentity);
						Phone = Phone.substring(2);
						PhoneNumberA.setText(Phone);
						user = logic.fetchUserDetails("+1".concat(PhoneNumberA.getText().trim()));
						if(user.getEmailID() != null && !StringUtils.isEmpty(user.getEmailID())){
							mailId = user.getEmailID();
						}
						nameA.setText(user.getName());
						String RoleA = user.getUserType();
						   if(RoleA.equals(Constants.MANAGER))
							   roleA.setText("Manager");
						   else if(RoleA.equals(Constants.CLERK))
							   roleA.setText("Clerk");
						   else if(RoleA.equals(Constants.CUSTOMER))
							   roleA.setText("Customer");
						   else
							   roleA.setText("Sytem Admin");
						ActivateUserPane.setDisable(false);
						searchLabel.setText("");
						loginIdInvalid.setText("");
						
					}
					else
					{
						loginIdInvalid.setText("User is already active");
						searchLabel.setText("");
					}
				}
				else
				{
					loginIdInvalid.setText("LoginId does not exist");
					searchLabel.setText("");
				}
			}
		}}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			searchLabel.setText("Connection Failed..Try Again");
		}
		
	}
	
	/**
	 * This method is executed when system admin clicks
	 * activate button while activating user
	 * Precondition: searchUserForActivation method displayed user details
	 * Postcondition: user is activated
	 * @param event
	 * @throws SQLException
	 * 
	 */
	@FXML
	public void UserActivation(ActionEvent event)
	{
		try {
			logic.Activate("+1".concat(PhoneNumberA.getText().trim()));
			if(mailId != null && !StringUtils.isEmpty(mailId)){
				String text = "Dear SuperRent User, Your login is activated by Admin.";
				String subject = "Your SuperRent Login activated";
				MailSender.send(text, subject, mailId);
			}
			mailId= "";
		 message.setText("User activated");
		 message.setTextFill(Color.GREEN);
		}
		catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			message.setText("Connection Failed..Try Again!");
		}
	}
	
	@FXML
	public void home(ActionEvent event){
		Navigator.loadStackPane(Navigator.SYSADMIN_HOME);
	}
	
	/**
	 * Precondition: system admin must be logged in
	 * Postcondition: system admin is logged out
	 * @param event
	 * @throws IOException
	 */
	@FXML
	public void logOut(ActionEvent event) throws IOException{
		Navigator.setSysAdmin(null);
		Navigator.setPhoneNumber(null);
		 FXMLLoader myLoader = new  FXMLLoader(getClass().getResource("/userManagementUI/LoginPage.fxml"));
	        Stage MainStage = new Stage();
	        Pane MainPagePane = (Pane)myLoader.load();
	        LoginController controller = (LoginController) myLoader.getController();
	        controller.SetStage(MainStage);
	        
	       // stage.setTitle("Login");
	        Scene myScene = new Scene(MainPagePane);        
	        MainStage.setScene(myScene);
	        MainStage.setTitle("SUPERRENT");
	        MainStage.setResizable(false);
	        MainStage.setWidth(605);
	        MainStage.setHeight(445);
	        MainStage.show();
	       sysAdminStage.close();
	}

    /**
     * 
     */
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		// TODO Auto-generated method stub
		if(page==1)
		{
		Validator.addTextLimiter(LoginIdA, 10);
		Validator.addTextLimiter(PhoneNoA, 10);
		page=0;
		}
		if(page==2)
		{
			Validator.addTextLimiter(LoginID, 10);
			Validator.addTextLimiter(PhoneNo, 10);
		}
	}
}
